<html>
<head>
<script type="text/javascript" src="/scripts/ajax.js"></script>
<script type="text/javascript">
function removeAllChildrenOfId(id) {
	var element = document.getElementById(id);
	if (!element) return;

	while (element.hasChildNodes()) {
		element.removeChild(element.firstChild);
	}
}
function appendChildToId(id, child) {
	var element = document.getElementById(id);
	if (!element) return;

	element.appendChild(child);
}
function buildPlayerRow(playerInfo) {
	var playerRow = document.createElement("tr");
	playerRow.appendChild(buildPlayerCell(document.createTextNode(playerInfo.key.name)));
	playerRow.appendChild(buildPlayerCell(document.createTextNode(playerInfo.name)));
	playerRow.appendChild(buildPlayerCell(buildPlayerButton(playerInfo.id, "Edit")));
	playerRow.appendChild(buildPlayerCell(buildPlayerButton(playerInfo.id, "Delete")));
	return playerRow;
}
function buildPlayerCell(node) {
	var playerCell = document.createElement("td");
	playerCell.appendChild(node);
	return playerCell;
}
function buildPlayerButton(id, action) {
	var playerButton = document.createElement("button");
	playerButton.value = id;
	playerButton.appendChild(document.createTextNode(action));
	return playerButton;
}

function loadPlayers() {
	ajaxRequest("playerInfo.jsp", function(json) {
		listPlayers(json);
	});
}
function clearPlayers() {
	ajaxRequest("playerInfo.jsp?action=clear", function(json) {
		listPlayers(json);
	});
}
function createPlayer() {
	var id   = document.getElementById("id").value;
	var name = document.getElementById("name").value;
	ajaxRequest("playerInfo.jsp?action=create&id="+id+"&name="+name, function(json) {
		listPlayers(json);
	});
}

function listPlayers(players) {
	removeAllChildrenOfId("playerInfo");
	for (var i = 0; i < players.length; ++i) {
		var playerInfo = players[i];
		appendChildToId("playerInfo", buildPlayerRow(playerInfo));
	}
}
</script>
</head>
<body>
<h1>Player Info</h1>
<table border>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tbody id="playerInfo">
</tbody>
<tfoot>
<tr>
<td><input id="id" /></td>
<td><input id="name" /></td>
</tr>
</tfoot>
</table>

<button onclick="loadPlayers()"/>Get Players</button>
<button onclick="clearPlayers()"/>Clear Players</button>
<button onclick="createPlayer()"/>Create Player</button>
</body>
</html>
